﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Wechat.Crawler.Blog;

public class WechatDbContext : DbContext
{
    public DbSet<Article> Articles { get; set; }

    public DbSet<WechatAccount> WechatAccounts { get; set; }

    public DbSet<TopicArticle> TopicArticles { get; set; }
    public DbSet<CollectionArticle> CollectionArticle { get; set; }

    public WechatDbContext(DbContextOptions options)
        : base(options) { }

    public static async Task InitializeAsync(WechatDbContext db)
    {
        await db.Database.MigrateAsync();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // if (!optionsBuilder.IsConfigured)
        // {
        //     //不同的数据库,只需要修改此处的连接字符串即可
        //     optionsBuilder.UseSqlite(@"Data Source=D:\\Wechat.CrawlerNew\\Article\\Output\\Db3\\Wechat.db");
        // }

        // 关闭ef core的命令行输出
        optionsBuilder.LogTo(Console.WriteLine, LogLevel.None);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Article>().ToTable("Article");
        modelBuilder.Entity<Article>().HasIndex(e => e.Url).IsUnique(); // url

        modelBuilder.Entity<WechatAccount>().ToTable("Wechat");
        modelBuilder.Entity<WechatAccount>().HasIndex(e => e.Biz).IsUnique(); // biz唯一

        modelBuilder.Entity<TopicArticle>().ToTable("TopicArticle");
        modelBuilder.Entity<TopicArticle>().HasIndex(e => e.Url).IsUnique(); // mid唯一

        modelBuilder.Entity<CollectionArticle>().ToTable("CollectionArticle");
        modelBuilder.Entity<CollectionArticle>().HasIndex(e => e.Url).IsUnique(); // mid唯一
    }
}
